import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
from src.ui.tkinter.styles.colors import BACKGROUND_MAIN, INPUT_BACKGROUND
from src.ui.tkinter.screens.creation_screen import show_creation_screen
from src.core.item_manager import delete_item, display_items

def show_selection_screen(parent: tk.Tk, items: dict) -> None:
    """Clear the parent window and display the bread management page (selection page)"""

    for widget in parent.winfo_children():
        widget.destroy()

    title_label = ttk.Label(
        parent,
        text="Bread Management",
        style="Title.TLabel"
    )
    title_label.pack(pady=(50, 30))

    add_btn = ttk.Button(
        parent,
        text="1. Add New Bread",
        style="Normal.TButton",
        command=lambda: show_creation_screen(parent, items)
    )
    add_btn.pack(pady=10, fill=tk.X, padx=250)  

    def show_all_breads():
        display_window = tk.Toplevel(parent)
        display_window.title("All Magic Breads")
        display_window.geometry("700x500")
        display_window.resizable(False, False)
        display_window.config(bg=BACKGROUND_MAIN)

        text_box = scrolledtext.ScrolledText(
            display_window,
            font=("Arial", 10),
            bg=INPUT_BACKGROUND,
            wrap=tk.WORD,
            state=tk.DISABLED  
        )
        text_box.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)

        import sys
        original_print = sys.stdout

        class PrintToText:
            def write(self, text):
                text_box.config(state=tk.NORMAL)
                text_box.insert(tk.END, text)
                text_box.config(state=tk.DISABLED)
                text_box.see(tk.END)  

            def flush(self):
                pass

        sys.stdout = PrintToText()
        display_items(items) 
        sys.stdout = original_print 

        close_btn = ttk.Button(
            display_window,
            text="Close",
            style="Cancel.TButton",
            command=display_window.destroy
        )
        close_btn.pack(pady=10)

    display_btn = ttk.Button(
        parent,
        text="2. Display All Breads",
        style="Normal.TButton",
        command=show_all_breads
    )
    display_btn.pack(pady=10, fill=tk.X, padx=250)

    delete_frame = ttk.Frame(parent, padding=(20, 10), style="Transparent.TFrame")
    delete_frame.pack(pady=20)

    delete_label = ttk.Label(
        delete_frame,
        text="Enter Bread ID to Delete:",
        style="Main.TLabel"
    )
    delete_label.grid(row=0, column=0, padx=10, pady=10)

    delete_id_var = tk.StringVar()
    delete_entry = ttk.Entry(
        delete_frame,
        textvariable=delete_id_var,
        style="Main.TEntry",
        width=20
    )
    delete_entry.grid(row=0, column=1, padx=10, pady=10)

    def confirm_delete():
        item_id = delete_id_var.get().strip()
        if not item_id:
            messagebox.showwarning("Warning", "Please enter a bread ID!")
            return
        updated_items = delete_item(items, item_id)

        if item_id not in updated_items:
            messagebox.showinfo(
                "Success",
                f"Item with ID {item_id} deleted successfully!"
            )
        else:
            messagebox.showerror(
                "Error",
                f"Item with ID {item_id} not found!"
            )
        delete_id_var.set("")  

    delete_btn = ttk.Button(
        delete_frame,
        text="3. Delete Bread",
        style="Normal.TButton",
        command=confirm_delete
    )
    delete_btn.grid(row=0, column=2, padx=10, pady=10)

    def go_to_launch_screen():
        from src.ui.tkinter.screens.launch_screen import show_launch_screen
        show_launch_screen(parent, items)

    back_btn = ttk.Button(
        parent,
        text="4. Back to Welcome Page",
        style="Cancel.TButton",
        command=go_to_launch_screen
    )
    back_btn.pack(pady=30, fill=tk.X, padx=300)